package com.comunicacion2;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class SelectorRedesActivity extends Activity {

	WifiManager wifi;
	private ScanRedesWifi scanRedesWifi;
	TextView etBuscando;
	ListView list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_selector_redes);

		etBuscando = (TextView) findViewById(R.id.text_buscando);

		list = (ListView) findViewById(R.id.list_redes);
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				// ListView Clicked item index
				int itemPosition = position;

				// ListView Clicked item value
				String itemValue = (String) list.getItemAtPosition(position);

				Intent i = getIntent();
				Bundle b = new Bundle();
				i.putExtra("Red", itemValue);
				setResult(RESULT_OK, i);

				// Finalizamos la Activity para volver a la anterior
				finish();

			}

		});

		wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

		createRegisterReceiverRedes();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.selector_redes, menu);
		return true;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(scanRedesWifi);

	}

	private void createRegisterReceiverRedes() {

		Handler h = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				String[] names = (String[]) msg.obj;
				ArrayAdapter<String> adaptador = new ArrayAdapter<String>(
						SelectorRedesActivity.this,
						android.R.layout.simple_list_item_1, names);
				list.setAdapter(adaptador);
				etBuscando.setText("");
			}
		};

		scanRedesWifi = new ScanRedesWifi(h, wifi);
		IntentFilter intFil = new IntentFilter(
				WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
		registerReceiver(scanRedesWifi, intFil);

	}

	public void buscarRedes(View view) {
		if (wifi.isWifiEnabled() == false) {
			Toast.makeText(this, "El wifi está desabilitado.. Habilitandolo..",
					Toast.LENGTH_LONG).show();
			wifi.setWifiEnabled(true);
		}
		wifi.startScan();
		Toast.makeText(this, "Buscando Redes....", Toast.LENGTH_SHORT).show();
		etBuscando.setText(" Buscando  . . .");
	}

}
